import { Form } from '@ant-design/compatible';
import { DownOutlined, PlusOutlined,InfoCircleOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card, Col, Checkbox,message,Tooltip} from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';
import DataLang from './DataLang';


// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
}
const { Option } = Select;
// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate, dataFormValues } = props;

  const parseData = (key:any,options:any) => {
    // console.log(options);
    var name:any = "";
    if(Array.isArray(options) && options.length>0){
      options.map(item=>{
        if(item.alias_key == key){
          name = item?.item_value;
        }
      })
    }
    return name
  }

  const parseDataItem = (key:any,options:any) => {
    var obj:any = {};
    if(Array.isArray(options) && options.length>0){
      options.map(item=>{
        if(item.alias_key == key){
          obj = item;
        }
      })
    }
    return obj
  }

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureLogo, setPictureLogo] = useState<any[]>([]);
  const [uploadLogoChanged, setUploadLogoChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [account_terms_close,setaccount_terms_close] = useState<boolean>(parseData('account_terms_close',dataFormValues) || false);
  const [account_privacy_close,setaccount_privacy_close] = useState<boolean>(parseData('account_privacy_close',dataFormValues) || false);
  const [account_cookie_close,setaccount_cookie_close] = useState<boolean>(parseData('account_cookie_close',dataFormValues) || false);
  const [account_delete_close, setAccount_delete_close] = useState<boolean>(parseData('account_cookie_close',dataFormValues) || false);

  const [dataLangModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const [fieldTitle, setFieldTitle] = useState<any>('');
  const [accountTermsJson, setAccountTermsJson] = useState<any>(parseDataItem('account_terms',dataFormValues).lang_json_arr || []);
  const [accountPrivacyJson, setAccountPrivacyJson] = useState<any>(parseDataItem('account_privacy',dataFormValues).lang_json_arr || []);
  const [accountCookieJson, setAccountCookieJson] = useState<any>(parseDataItem('account_cookie',dataFormValues).lang_json_arr || []);
  const [accountDeleteJson, setAccountDeleteJson] = useState<any>(parseDataItem('account_delete',dataFormValues).lang_json_arr || []);


  const [nameListLang, setnameList] = useState<any>(common?.languagesOption);
  

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      
      console.log(fieldsValue.register_login_flow);
      console.log("submit fields ", fieldsValue)
      //请求当前一组配置参数，tag=policies
      var submitValue = [
          {
            alias_key: 'policies',
            item_type:'system',
            dict_item_arr: [
              {
                "alias_key": "account_terms_close",
                "item_value": fieldsValue.account_terms_close,
                'item_type':"radio",
              },
              {
                "alias_key": "account_terms",
                "item_value": fieldsValue.account_terms,
                'item_type':"textarea",
                'lang_json': accountTermsJson,
              },
              {
                "alias_key": "account_privacy_close",
                "item_value": fieldsValue.account_privacy_close,
                'item_type':"radio",
              },
              {
                "alias_key": "account_privacy",
                "item_value": fieldsValue.account_privacy,
                'item_type':"textarea",
                'lang_json': accountPrivacyJson,
              },
              {
                "alias_key": "account_cookie_close",
                "item_value": fieldsValue.account_cookie_close,
                'item_type':"radio",
              },
              {
                "alias_key": "account_cookie",
                "item_value": fieldsValue.account_cookie,
                'item_type':"textarea",
                'lang_json': accountCookieJson,
              },
              {
                "alias_key": "account_delete_close",
                "item_value": fieldsValue.account_delete_close,
                'item_type':"radio",
              },
              {
                "alias_key": "account_delete",
                "item_value": fieldsValue.account_delete,
                'item_type':"textarea",
                'lang_json': accountDeleteJson,
              },
            ]
          }
      ]
      // 如果更新成功之后，重置表单
      updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
        console.log('handleSubmit then success is ', JSON.stringify(submitValue))
        if(res.code == 0){
          message.success('保存成功')
        }
      })

    });
  };

  // 表单提交
  const handleSubmitDataForm = (value:any,title:any) => {
    console.log(value,241)
    setnameList(value)
    if(title == "account_terms"){
      setAccountTermsJson(value);
    }else if(title == "account_privacy"){
      setAccountPrivacyJson(value);
    }else if(title == "account_cookie"){
      setAccountCookieJson(value);
    }else if(title == "account_delete"){
      setAccountDeleteJson(value);
    }
    handleDataModalVisible(false)
  }

 

  // 弹出框
  // @ts-ignore
  return <Card>
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} style={{marginBottom: 15}}
        label={
          <span>
            <FormattedMessage id="服务条款" />
          </span>
        }
        >
          {form.getFieldDecorator('account_terms_close', {
            initialValue: parseData('account_terms_close',dataFormValues),
          })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>启用</Radio>
            </Radio.Group>
          )}
      </FormItem>
    </Col>
    {
      form.getFieldValue('account_terms_close') == true && 
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({id: 'terms of service'})} style={{marginBottom: 15}}>
          {form.getFieldDecorator('account_terms', {
            initialValue: accountTermsJson.length>0?accountTermsJson[0].lang_content:'',
            // rules: [],
          })(<TextArea style={{cursor:"pointer"}} readOnly rows={3} placeholder={'支持 Markdown 语法，支持多语言'} onClick={() => {
            setFieldTitle('account_terms');
            if(accountTermsJson && accountTermsJson.length>0){
              setnameList(accountTermsJson);
            }else{
              setnameList(JSON.parse(JSON.stringify(common.languagesOption)));
            }
            handleDataModalVisible(true);
           }}/>)}
        </FormItem>
      </Col>
    }
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} style={{marginBottom: 15}}
        label={
          <span>
            <FormattedMessage id="隐私权政策" />
          </span>
        }
        >
          {form.getFieldDecorator('account_privacy_close', {
            initialValue: parseData('account_privacy_close',dataFormValues),
          })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>启用</Radio>
            </Radio.Group>
          )}
      </FormItem>
    </Col>
    {
      form.getFieldValue('account_privacy_close') == true && 
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({id: 'Privacy Policy'})} style={{marginBottom: 15}}>
          {form.getFieldDecorator('account_privacy', {
            initialValue: accountPrivacyJson.length>0?accountPrivacyJson[0].lang_content:'',
            // rules: [],
          })(<TextArea style={{cursor:"pointer"}} readOnly rows={3} placeholder={'支持 Markdown 语法，支持多语言'} onClick={() => {
            setFieldTitle('account_privacy');
            if(accountPrivacyJson && accountPrivacyJson.length>0){
              setnameList(accountPrivacyJson);
            }else{
              setnameList(JSON.parse(JSON.stringify(common.languagesOption)));
            }
            handleDataModalVisible(true);
           }}/>)}
        </FormItem>
      </Col>
    }
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} style={{marginBottom: 15}}
        label={
          <span>
            <FormattedMessage id="Cookie 政策" />
          </span>
        }
        >
          {form.getFieldDecorator('account_cookie_close', {
            initialValue: parseData('account_cookie_close',dataFormValues),
          })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>启用</Radio>
            </Radio.Group>
          )}
      </FormItem>
    </Col>
    {
      form.getFieldValue('account_cookie_close') == true && 
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({id: 'Cookie Policy'})} style={{marginBottom: 15}}>
          {form.getFieldDecorator('account_cookie', {
            initialValue: accountCookieJson.length>0?accountCookieJson[0].lang_content:'',
            // rules: [],
          })(<TextArea style={{cursor:"pointer"}} readOnly rows={3} placeholder={'支持 Markdown 语法，支持多语言'} onClick={() => {
            setFieldTitle('account_cookie');
            if(accountCookieJson && accountCookieJson.length>0){
              setnameList(accountCookieJson);
            }else{
              setnameList(JSON.parse(JSON.stringify(common.languagesOption)));
            }
            handleDataModalVisible(true);
           }}/>)}
        </FormItem>
      </Col>
    }
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} style={{marginBottom: 15}}
        label={
          <span>
            <FormattedMessage id="注销说明" />
          </span>
        }
        >
          {form.getFieldDecorator('account_delete_close', {
            initialValue: parseData('account_delete_close',dataFormValues),
          })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>启用</Radio>
            </Radio.Group>
          )}
      </FormItem>
    </Col>
    {
      form.getFieldValue('account_delete_close') == true && 
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({id : 'cancellation policy'})} style={{marginBottom: 15}}>
          {form.getFieldDecorator('account_delete', {
            initialValue: accountDeleteJson.length>0?accountDeleteJson[0].lang_content:'',
            // rules: [],
          })(<TextArea style={{cursor:"pointer"}} readOnly rows={3} placeholder={'支持 Markdown 语法，支持多语言'} onClick={() => {
            setFieldTitle('account_delete');
            if(accountDeleteJson && accountDeleteJson.length>0){
              setnameList(accountDeleteJson);
            }else{
              setnameList(JSON.parse(JSON.stringify(common.languagesOption)));
            }
            handleDataModalVisible(true);
           }}/>)}
        </FormItem>
      </Col>
    }
    <Col span={24}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okHandle()}}>提交保存</Button>
      </div>
    </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
    <DataLang
        dataModalVisible={dataLangModalVisible}
        isUpdate={isUpdate}
        dataFormValues={dataFormValues}
        common={common || {}}
        nameList={nameListLang}
        title={fieldTitle}
        onSubmit={handleSubmitDataForm}
        onCancel={() => handleDataModalVisible(false)}
    />
  </Card>;
};

export default Form.create<DataFormProps>()(DataForm);
